package org.noote.roby.monitor;

import org.noote.libs.tcpip.helper.Helper_WiFi;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class SearchConnexion_Activity extends Activity {
	private static final String LOG_TAG = "SearchConnexion_Activity";
	
	private String m_sControllerName = "NooTe's Controller";
	private String m_sControllerVersion = "0.2";

	private int m_iServerPort = -1;

	private String m_sCurrentIPAddress = "0.0.0.0";
	
	private int m_iScanIPServerMin = 1, m_iScanIPServerMax = 255;	
	protected static final int SCAN_MSG_IND = 0;
	protected static final int SCAN_MSG_FINISH = 1;

	private static final int REFRESH_OK = 0;

	protected ProgressDialog m_mScanProgressDialog = null;
	ArrayList<HashMap<String, String>> m_listFavoritesIPAdresses = new ArrayList<HashMap<String, String>>();
	ArrayList<HashMap<String, String>> m_listScannedIPAdresses = new ArrayList<HashMap<String, String>>();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.controller_askconnexion);

        loadSettings();
        getCurrentIPAddress();
		
		EditText editCurrentIP = (EditText) findViewById(R.id.editCurrentIP);
		editCurrentIP.setText(m_sCurrentIPAddress + ":" + String.valueOf(m_iServerPort));
		
		Button buttonScan = (Button) findViewById(R.id.buttonScan);
		buttonScan.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				scanLocalIPAdresses();
			}
		});
		
		ListView listLocalIPAddresses = (ListView)findViewById(R.id.listLocalIPAddresses);
		listLocalIPAddresses.setOnItemClickListener(new OnItemClickListener() {
        	@Override
            public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

        		@SuppressWarnings("unchecked")
				final HashMap<String, String> map = (HashMap<String, String>)parent.getItemAtPosition(position);
        		
        		String sAction = map.get("action");
        		if(sAction.equalsIgnoreCase("ready"))
        		{
        			Log.d(LOG_TAG, "Intent(RobotController_Activity)");
        			
        			Bundle bundle = new Bundle();
        			bundle.putString("server_ip", map.get("ip"));
        			bundle.putInt("server_port", m_iServerPort);
        			Intent intent = new Intent(SearchConnexion_Activity.this, RobotController_Activity.class);
    	    		intent.putExtras(bundle);
    	    		startActivity(intent);
        		}
        	}
          });
		
		if(m_listFavoritesIPAdresses.size()>0)
		{
			SeparatedListAdapter adapter = new SeparatedListAdapter(getBaseContext()); 
	        adapter.addSection("Favorite Adresses", new SimpleAdapter (getBaseContext(), m_listFavoritesIPAdresses, R.layout.listview_item_ipaddress,
	                new String[] {"ip", "desc"}, new int[] {R.id.ipaddress, R.id.description}));	            
	        listLocalIPAddresses.setAdapter(adapter);
		}
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.controller, menu);
        return true;
    }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.itemSetting:
    		Intent intent = new Intent(this, Preferences_Controller.class);
    		startActivityForResult(intent, REFRESH_OK);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
	     switch (requestCode) {
	        case REFRESH_OK:
		   	     switch (resultCode) {
			        case RESULT_OK:
			        	loadSettings();
			        	getCurrentIPAddress();
			        	break;
			     }
	             break;
	     }
	}
	
	private void getCurrentIPAddress() {
		Log.d(LOG_TAG, "getCurrentIPAddress()");
		
		m_sCurrentIPAddress = Helper_WiFi.getCurrentIPAddress_WiFi_Only(this, true);
		if(m_sCurrentIPAddress == "")
		{
			new AlertDialog.Builder(this)
			.setTitle("Not active connexion detected...")
			.setPositiveButton("Ok",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog,
								int whichButton) {
							finish();
						}
					}).show();
			return;
		}
	}

	private void loadSettings() {
		Log.d(LOG_TAG, "loadSettings()");
		
        SharedPreferences settings = getSharedPreferences(Main_Activity.PREFS_NAME, 0);
        m_iServerPort = Integer.valueOf(settings.getString(Main_Activity.PREFS_NAME_SERVER_PORT, String.valueOf(m_iServerPort)));
        m_iScanIPServerMin = Integer.valueOf(settings.getString(Main_Activity.PREFS_NAME_SCAN_MIN,  String.valueOf(m_iScanIPServerMin)));
        m_iScanIPServerMax = Integer.valueOf(settings.getString(Main_Activity.PREFS_NAME_SCAN_MAX,  String.valueOf(m_iScanIPServerMax)));
        m_sControllerName = settings.getString(Main_Activity.PREFS_NAME_CONTROLLER_NAME, m_sControllerName);
        
        boolean bNeedReSaving = false;
        if(m_iServerPort<1) { m_iServerPort = 8086; bNeedReSaving=true; }
        else if(m_iServerPort>65535) { m_iServerPort = 65535; bNeedReSaving=true; }
        if(m_iScanIPServerMin<1) { m_iScanIPServerMin = 1; bNeedReSaving=true; }
        else if(m_iScanIPServerMin>255) { m_iScanIPServerMin = 255; bNeedReSaving=true; }
        if(m_iScanIPServerMax<1) { m_iScanIPServerMax = 1; bNeedReSaving=true; }
        else if(m_iScanIPServerMax>255) { m_iScanIPServerMax = 255; bNeedReSaving=true; }
        if(m_iScanIPServerMax<m_iScanIPServerMin) { m_iScanIPServerMax = m_iScanIPServerMin; bNeedReSaving=true; }
        if(m_sControllerName.length() == 0) { m_sControllerName = "NooTe's Controller"; bNeedReSaving=true; }
        if(bNeedReSaving)
        {
        	SharedPreferences.Editor editor = settings.edit();
        	editor.putString(Main_Activity.PREFS_NAME_SERVER_PORT, String.valueOf(m_iServerPort));
        	editor.putString(Main_Activity.PREFS_NAME_SCAN_MIN, String.valueOf(m_iScanIPServerMin));
        	editor.putString(Main_Activity.PREFS_NAME_SCAN_MAX, String.valueOf(m_iScanIPServerMax));
        	editor.putString(Main_Activity.PREFS_NAME_CONTROLLER_NAME, m_sControllerName);
        	editor.commit();
        }
	}
	
	private final Handler m_ScanHandler = new Handler() {
	    @Override
		public void handleMessage(Message msg) {
	        switch (msg.what) {
	        case SCAN_MSG_IND:
	            if (m_mScanProgressDialog.isShowing()) {
	            	m_mScanProgressDialog.setMessage(((String) msg.obj));
	            }
	            break;
	        case SCAN_MSG_FINISH:
	            if (m_mScanProgressDialog.isShowing()) {
	            	m_mScanProgressDialog.dismiss();
	            }

	            SeparatedListAdapter adapter = new SeparatedListAdapter(getBaseContext());
	            if(m_listFavoritesIPAdresses.size()>0)
	            	adapter.addSection("Favorite Adresses", new SimpleAdapter (getBaseContext(), m_listScannedIPAdresses, R.layout.listview_item_ipaddress,
	                    new String[] {"ip", "desc"}, new int[] {R.id.ipaddress, R.id.description}));	            
	            if(m_listScannedIPAdresses.size()>0)
	            	adapter.addSection("Adresses found", new SimpleAdapter (getBaseContext(), m_listScannedIPAdresses, R.layout.listview_item_ipaddress,
	                    new String[] {"ip", "desc"}, new int[] {R.id.ipaddress, R.id.description}));
	            ListView lv = (ListView)findViewById(R.id.listLocalIPAddresses);
	            lv.setAdapter(adapter);
	            
	            break;
	        }
	    }
	};

	void scanLocalIPAdresses() {

		m_mScanProgressDialog = ProgressDialog.show(this, "Scan IP Addresses", "", true);
       
		new Thread((new Runnable() {
	        @Override
	        public void run() {

	    		String [] s = m_sCurrentIPAddress.split("\\.");
	    		if(s.length != 4)
	    		{
					Message msg = m_ScanHandler.obtainMessage(SCAN_MSG_FINISH, null);
					m_ScanHandler.sendMessage(msg);

	    			Toast.makeText(getApplicationContext(),
	    					"Invalid IP Adress. Please check it !", Toast.LENGTH_LONG)
	    					.show();

	    			return;
	    		}
	        	
	    		for(int i=m_iScanIPServerMin; i<=m_iScanIPServerMax; i++)
	    		{
	    			String sIpToCheck = String.format("%s.%s.%s.%d", s[0], s[1], s[2], (i & 0xff));
	    			
	    			String sMsg = "From\t: "+String.format("%s.%s.%s.%d", s[0], s[1], s[2], m_iScanIPServerMin);
	    			sMsg += "\nTo\t: "+String.format("%s.%s.%s.%d", s[0], s[1], s[2], m_iScanIPServerMax);
	    			sMsg += "\nCurrent\t"+sIpToCheck;
	    			sMsg += "\nLeft "+String.valueOf(m_iScanIPServerMax-i)+" ip adresses";

	    			Message msg = m_ScanHandler.obtainMessage(SCAN_MSG_IND, sMsg);
					m_ScanHandler.sendMessage(msg);

					IPProtocole ipp = new IPProtocole();
					ResponseHello hello = ipp.sendHelloToServer(sIpToCheck, m_iServerPort, m_sControllerName, m_sControllerVersion);
					if(hello != null)
	    			{
	    				HashMap<String, String> map = new HashMap<String, String>();
	    	    		map.put("ip", sIpToCheck);

	    	    		map.put("action", "ready");
    	    			map.put("desc", "Core's name : "+hello.sName+"\nVersion "+hello.sVersion);
    	    		
	    	    		m_listScannedIPAdresses.add(map);	    		
	    			}
	    		}

				Message msg = m_ScanHandler.obtainMessage(SCAN_MSG_FINISH, null);
				m_ScanHandler.sendMessage(msg);
	        }
	    })).start();
	}
	
	@Override
	public void onBackPressed()
	{
		finish();
	}
}
